package android.theHead;

import java.text.DecimalFormat;
import java.util.Calendar;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

public class TeamData extends Activity{
	Context thisContext;
	public HeadChangeReceiver receiver = null;
	
	TeamDBAdapter teamDB;
	Cursor c;
	
	DecimalFormat round = new DecimalFormat("0.000000"); 
	private DecimalFormat oneDec = new DecimalFormat("00.0");
	private DecimalFormat zeroDec = new DecimalFormat("00");
	private TextView tv_tempo;
	private TextView tv_time;
	private TextView tv_distance;
	private TextView tv_ranking;
	private TextView tv_speed;
	private TextView tv_name;
	private ImageView tv_logo;

	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		
		thisContext = this;
		
		setContentView(R.layout.rowmode);
		
		teamDB = new TeamDBAdapter(this);
		teamDB.open();

		Intent receivedIntent = this.getIntent();
		int teamID = receivedIntent.getIntExtra("teamID", 0);

		c = teamDB.getTeamData(teamID);
		
		tv_name = (TextView) findViewById(R.id.rmHeading_teamName);
        tv_tempo = (TextView) findViewById(R.id.rmTempo_value);
        tv_speed = (TextView) findViewById(R.id.rmSpeed_value);
        tv_time = (TextView) findViewById(R.id.rmTime_value);
        tv_logo = (ImageView) findViewById(R.id.rmLogo_clubLogo);
	}
	
	public void onResume(){
		super.onResume();

		IntentFilter filter;
		filter = new IntentFilter(BackgroundService.NEW_HEAD_DATA	);
		receiver = new HeadChangeReceiver();
		registerReceiver(receiver, filter);
	}

	public void onDestroy(){
		super.onDestroy();

		Log.i("ListView", "onDestroy");
		c.close();
		teamDB.close();

		unregisterReceiver(receiver);
	}
	
	public void updateFields(Cursor c){
		c.moveToLast();
		Calendar cal = Calendar.getInstance();
		int hour = cal.get(Calendar.MINUTE);
		int minute = cal.get(Calendar.SECOND);
		
		tv_tempo.setText(oneDec.format(c.getFloat(c.getColumnIndex("tempo"))));
		tv_speed.setText(oneDec.format(c.getFloat(c.getColumnIndex("speed"))));
		tv_name.setText(c.getString(c.getColumnIndex("teamName")));
		tv_time.setText(zeroDec.format(hour)+":"+zeroDec.format(minute));
		
		int drawable = getResources().getIdentifier(c.getString(c.getColumnIndex("clubID")).toLowerCase(), "drawable", "android.theHead");
		tv_logo.setImageResource(drawable);
		

	}

	public class HeadChangeReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getIntExtra(BackgroundService.HEAD_DATA_CHANGED, 0)== BackgroundService.READINGS_TABLE_UPDATED){
				Log.i("TeamData", "ReadingsTable changed, updating!");
				c.requery();
				updateFields(c);
			}
		}
	}	
}

